package com.saas.platform.platformservicedemo.base.configure;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.saas.platform.platformservicedemo.base.advice.ReqFormParamrAdvice;
import com.saas.platform.platformservicedemo.base.interceptor.AccessLogInterceptor;
import com.saas.platform.platformservicedemo.base.interceptor.AuthTokenInterceptor;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

@Configuration
public class WebAppConfigurer extends WebMvcConfigurerAdapter {
	
	@Bean
	public AuthTokenInterceptor authTokenInterceptor(){
		return new AuthTokenInterceptor();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new AccessLogInterceptor())
			.addPathPatterns("/open/api/platformservicedemo/**");
		
		registry.addInterceptor(authTokenInterceptor())
			;

	}

	@Override
	public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
		super.addArgumentResolvers(argumentResolvers);
		argumentResolvers.add(0, new ReqFormParamrAdvice());
	}
	
	@LoadBalanced
	@Bean
	public RestTemplate loadBalanced(RestTemplateBuilder builder) {
		RestTemplate restTemplate = builder.build();
		restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
		return restTemplate;
	}
	
	@Primary
	@Bean
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		RestTemplate restTemplate = builder.build();
		restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
		return restTemplate;
	}

      
    @Bean  
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){  
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();  
        factory.setReadTimeout(5000);//ms  
        factory.setConnectTimeout(15000);//ms  
        return factory;  
    } 

}
